package com.css.zfzx.sjcj.modules.hddcB2GeomorphySvyProjectTable.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSONObject;
import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.constants.PlatformConstants;
import com.css.bpm.platform.sys.dict.repository.entity.DictItemEntity;
import com.css.bpm.platform.utils.PlatformDateUtils;
import com.css.bpm.platform.utils.PlatformObjectUtils;
import com.css.bpm.platform.utils.PlatformPageUtils;
import com.css.bpm.platform.utils.PlatformSessionUtils;
import com.css.bpm.platform.utils.UUIDGenerator;
import com.css.zfzx.sjcj.common.utils.EasyPoiExcelUtil;
import com.css.zfzx.sjcj.common.utils.UpdateUtil;
import com.css.zfzx.sjcj.modules.hddcB2GeomorphySvyProjectTable.repository.HddcB2GeomorphysvyprojecttableNativeRepository;
import com.css.zfzx.sjcj.modules.hddcB2GeomorphySvyProjectTable.repository.HddcB2GeomorphysvyprojecttableRepository;
import com.css.zfzx.sjcj.modules.hddcB2GeomorphySvyProjectTable.repository.entity.HddcB2GeomorphysvyprojecttableEntity;
import com.css.zfzx.sjcj.modules.hddcB2GeomorphySvyProjectTable.service.HddcB2GeomorphysvyprojecttableService;
import com.css.zfzx.sjcj.modules.hddcB2GeomorphySvyProjectTable.viewobjects.HddcB2GeomorphysvyprojecttablePageVO;
import com.css.zfzx.sjcj.modules.hddcB2GeomorphySvyProjectTable.viewobjects.HddcB2GeomorphysvyprojecttableQueryParams;
import com.css.zfzx.sjcj.modules.hddcB2GeomorphySvyProjectTable.viewobjects.HddcB2GeomorphysvyprojecttableVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 地貌调查数据-微地貌测量工程-属性表管理
 * @author zyb
 * @date 2020-12-07
 */
@Service
public class HddcB2GeomorphysvyprojecttableServiceImpl implements HddcB2GeomorphysvyprojecttableService {

    private final HddcB2GeomorphysvyprojecttableRepository hddcB2GeomorphysvyprojecttableRepository;
    private final HddcB2GeomorphysvyprojecttableNativeRepository hddcB2GeomorphysvyprojecttableNativeRepository;
    private final MicroReliefMeasureEngineeringExcelVerifyHandler microReliefMeasureEngineeringExcelVerifyHandler;

    @Autowired
    public HddcB2GeomorphysvyprojecttableServiceImpl(HddcB2GeomorphysvyprojecttableRepository hddcB2GeomorphysvyprojecttableRepository,
                                                     HddcB2GeomorphysvyprojecttableNativeRepository hddcB2GeomorphysvyprojecttableNativeRepository,
                                                     MicroReliefMeasureEngineeringExcelVerifyHandler microReliefMeasureEngineeringExcelVerifyHandler) {
        this.hddcB2GeomorphysvyprojecttableRepository = hddcB2GeomorphysvyprojecttableRepository;
        this.hddcB2GeomorphysvyprojecttableNativeRepository = hddcB2GeomorphysvyprojecttableNativeRepository;
        this.microReliefMeasureEngineeringExcelVerifyHandler = microReliefMeasureEngineeringExcelVerifyHandler;
    }

    @Override
    public JSONObject queryHddcB2Geomorphysvyprojecttables(HddcB2GeomorphysvyprojecttableQueryParams queryParams, int curPage, int pageSize, String sort, String order) {
        Page<HddcB2GeomorphysvyprojecttablePageVO> hddcB2GeomorphysvyprojecttablePage = this.hddcB2GeomorphysvyprojecttableNativeRepository.queryHddcB2Geomorphysvyprojecttables(queryParams, curPage, pageSize, sort, order);
        return PlatformPageUtils.formatPageData(hddcB2GeomorphysvyprojecttablePage);
    }

    @Override
    public HddcB2GeomorphysvyprojecttableEntity getHddcB2Geomorphysvyprojecttable(String id) {
        return this.hddcB2GeomorphysvyprojecttableRepository.findById(id).orElse(null);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcB2GeomorphysvyprojecttableEntity saveHddcB2Geomorphysvyprojecttable(HddcB2GeomorphysvyprojecttableEntity hddcB2Geomorphysvyprojecttable) {
        String uuid = UUIDGenerator.getUUID();
        hddcB2Geomorphysvyprojecttable.setUuid(uuid);
        hddcB2Geomorphysvyprojecttable.setCreateUser(PlatformSessionUtils.getUserId());
        Timestamp now = PlatformDateUtils.getCurrentTimestamp();
        hddcB2Geomorphysvyprojecttable.setCreateTime(now);
        hddcB2Geomorphysvyprojecttable.setUpdateTime(now);
        hddcB2Geomorphysvyprojecttable.setIsValid(PlatformConstants.Y);
        hddcB2Geomorphysvyprojecttable.setQualityinspectionStatus(PlatformConstants.N);
        hddcB2Geomorphysvyprojecttable.setExtends10(PlatformConstants.Y);
        this.hddcB2GeomorphysvyprojecttableRepository.save(hddcB2Geomorphysvyprojecttable);
        return hddcB2Geomorphysvyprojecttable;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcB2GeomorphysvyprojecttableEntity updateHddcB2Geomorphysvyprojecttable(HddcB2GeomorphysvyprojecttableEntity hddcB2Geomorphysvyprojecttable) {
        HddcB2GeomorphysvyprojecttableEntity entity = hddcB2GeomorphysvyprojecttableRepository.findById(hddcB2Geomorphysvyprojecttable.getUuid()).get();
        UpdateUtil.copyNullProperties(entity, hddcB2Geomorphysvyprojecttable);
        hddcB2Geomorphysvyprojecttable.setUpdateUser(PlatformSessionUtils.getUserId());
        hddcB2Geomorphysvyprojecttable.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        this.hddcB2GeomorphysvyprojecttableRepository.save(hddcB2Geomorphysvyprojecttable);
        return hddcB2Geomorphysvyprojecttable;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteHddcB2Geomorphysvyprojecttables(List<String> ids) {
        List<HddcB2GeomorphysvyprojecttableEntity> hddcB2GeomorphysvyprojecttableList = this.hddcB2GeomorphysvyprojecttableRepository.findAllById(ids);
        if (!PlatformObjectUtils.isEmpty(hddcB2GeomorphysvyprojecttableList) && hddcB2GeomorphysvyprojecttableList.size() > 0) {
            for (HddcB2GeomorphysvyprojecttableEntity hddcB2Geomorphysvyprojecttable : hddcB2GeomorphysvyprojecttableList) {
//                this.hddcB2GeomorphysvyprojecttableRepository.delete(hddcB2Geomorphysvyprojecttable);
                hddcB2Geomorphysvyprojecttable.setIsValid(PlatformConstants.N);
                hddcB2Geomorphysvyprojecttable.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcB2Geomorphysvyprojecttable.setUpdateTime(new Date());
                this.hddcB2GeomorphysvyprojecttableRepository.save(hddcB2Geomorphysvyprojecttable);
            }
        }
    }

    @Override
    public List<DictItemEntity> getValidDictItemsByDictCode(String dictCode) {
        return PlatformAPI.getDictAPI().getValidDictItemsByDictCode(dictCode);
    }

    @Override
    public void exportFile(HddcB2GeomorphysvyprojecttableQueryParams queryParams, HttpServletResponse response) {
        List<HddcB2GeomorphysvyprojecttableEntity> yhDisasterEntities = hddcB2GeomorphysvyprojecttableNativeRepository.exportYhDisasters(queryParams);
        List<HddcB2GeomorphysvyprojecttableVO> list = new ArrayList<>();
        for (HddcB2GeomorphysvyprojecttableEntity entity : yhDisasterEntities) {
            HddcB2GeomorphysvyprojecttableVO yhDisasterVO = new HddcB2GeomorphysvyprojecttableVO();
            BeanUtils.copyProperties(entity, yhDisasterVO);
            list.add(yhDisasterVO);
        }
        EasyPoiExcelUtil.exportExcel(list, "微地貌测量工程", "微地貌测量工程",
                HddcB2GeomorphysvyprojecttableVO.class, "微地貌测量工程.xls", response);
    }

    @Override
    public String importExcel(MultipartFile file, HttpServletResponse response) {
        try {
            // 返回的消息
            StringBuilder returnMsg = new StringBuilder();
            // 导入的参数信息
            ImportParams params = new ImportParams();
            // 设置简析的第一行
            params.setHeadRows(1);
            // 是否需要校验
            params.setNeedVerify(true);
            params.setVerifyHandler(microReliefMeasureEngineeringExcelVerifyHandler);
            // 获取到Excel数据
            ExcelImportResult<HddcB2GeomorphysvyprojecttableVO> result = ExcelImportUtil.importExcelMore(file.getInputStream(), HddcB2GeomorphysvyprojecttableVO.class, params);
            if (result.isVerifyFail()) {
                // 校验返回失败行信息
                for (HddcB2GeomorphysvyprojecttableVO yhDisasterVO : result.getFailList()) {
                    returnMsg.append("第").append(yhDisasterVO.getRowNum()).append("行").append(yhDisasterVO.getErrorMsg()).append("<br/>");
                }
                if (returnMsg.length() > 0)
                    return returnMsg.toString();
            }
            List<HddcB2GeomorphysvyprojecttableVO> list = result.getList();
            //保存
            saveDisasterList(list);
            return returnMsg.append("成功导入").append(result.getList().size()).toString();
        } catch (Exception e) {
            return "导入失败，请检查数据正确性";
        }
    }

    /**
     * 批量存入库表并且返回错误数量
     */
    public void saveDisasterList(List<HddcB2GeomorphysvyprojecttableVO> list) {
        for (HddcB2GeomorphysvyprojecttableVO hddcB2GeomorphysvyprojecttableVO : list) {
            HddcB2GeomorphysvyprojecttableEntity yhDisasterEntity = new HddcB2GeomorphysvyprojecttableEntity();
            BeanUtils.copyProperties(hddcB2GeomorphysvyprojecttableVO, yhDisasterEntity);
            saveHddcB2Geomorphysvyprojecttable(yhDisasterEntity);
        }
    }

    /**
     * 逻辑删除-根据项目id删除数据
     */
    @Override
    public void deleteByProjectId(List<String> projectIds) {
        List<HddcB2GeomorphysvyprojecttableEntity> hddcDataList = this.hddcB2GeomorphysvyprojecttableRepository.queryByProjectId(projectIds);
        if (!PlatformObjectUtils.isEmpty(hddcDataList) && hddcDataList.size() > 0) {
            for (HddcB2GeomorphysvyprojecttableEntity entity : hddcDataList) {
                entity.setUpdateUser(PlatformSessionUtils.getUserId());
                entity.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                entity.setIsValid(PlatformConstants.N);
                this.hddcB2GeomorphysvyprojecttableRepository.save(entity);
            }
        }
    }

    /**
     * 逻辑删除-根据任务id删除数据
     */
    @Override
    public void deleteByTaskId(List<String> taskId) {
        List<HddcB2GeomorphysvyprojecttableEntity> hddcDataList = this.hddcB2GeomorphysvyprojecttableRepository.queryByTaskId(taskId);
        if (!PlatformObjectUtils.isEmpty(hddcDataList) && hddcDataList.size() > 0) {
            for (HddcB2GeomorphysvyprojecttableEntity entity : hddcDataList) {
                entity.setUpdateUser(PlatformSessionUtils.getUserId());
                entity.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                entity.setIsValid(PlatformConstants.N);
                this.hddcB2GeomorphysvyprojecttableRepository.save(entity);
            }
        }
    }

}
